package com.gadglet.cron;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class SessionCleanupServlet extends HttpServlet {

	/**
         * 
         */
	private static final long serialVersionUID = 7819922897125461099L;
	Logger log = Logger.getLogger(this.getClass().getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String  nameSpace = NamespaceManager.get();
		NamespaceManager.set("");
		
		// maximum
		int limit = 10000;
		Query query = new Query("_ah_SESSION");
		// expired a week ago
		query.addFilter("_expires", FilterOperator.LESS_THAN,
				System.currentTimeMillis() - 604800000/* 7*24*3600*1000 */);
		query.setKeysOnly();
		ArrayList<Key> killList = new ArrayList<Key>();
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		PreparedQuery pq = datastore.prepare(query);
		Iterable<Entity> entities = pq.asIterable(FetchOptions.Builder
				.withLimit(limit));

		log.warning("Starting old session clearing");

		try {
			for (Entity expiredSession : entities) {
				Key key = expiredSession.getKey();
				killList.add(key);

			}
			datastore.delete(killList);
			
			log.warning(killList.size() + " sessions deleted");

		} catch (Exception e) {
			log.warning("problem session clearing " + e.getMessage());
		}
		NamespaceManager.set(nameSpace);
	}
}
